package sessionBeans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entityBeans.Contact;
import entityBeans.ContactGroup;

@Stateless(mappedName = "ContactGroupBeanEntity")
public class GestionContactGroupBeanEntity implements GestionContactGroupLocal {

	@PersistenceContext
	EntityManager em;

	@Override
	public List<String> search() {
		List<String> groups = (List<String>) em.createQuery(
				"select g.groupName from ContactGroup as g").getResultList();
		return groups.size() == 0 ? null : groups;
	}

	@Override
	public ContactGroup find(String name) {
		Query q = em
				.createQuery("select g from ContactGroup g where g.groupName= :gname");
		q.setParameter("gname", name);
		ContactGroup group = (ContactGroup) q.getSingleResult();
		return group;
	}

	@Override
	public List<ContactGroup> getAllGroup() {
		List<ContactGroup> groups = em.createQuery(
				"Select g from ContactGroup g").getResultList();

		return groups.size() == 0 ? null : groups;
	}

	@Override
	public void updateGroup(ContactGroup grp, Contact c) {
		ContactGroup cg = em.find(ContactGroup.class, grp.getGroupID());
		cg.getContacts().add(c);
		em.flush();
	}

	@Override
	public void updateGroupByName(String grName, Contact c) {
		ContactGroup cg = this.find(grName);
		if (cg != null)
			cg.getContacts().add(c);
		em.flush();
	}

	@Override
	public ContactGroup addGroup(ContactGroup cg) {
		em.persist(cg);
		return cg;
	}

	@Override
	public void delete(String grName) {

		ContactGroup cg = find(grName);
		int i = cg.getGroupID();
		if (cg == null)
			return;
		// 1st delete the reference id
		Query q = em
				.createNativeQuery("DELETE FROM contactgroup_contact WHERE books_groupID = :id");
		q.setParameter("id", i);
		q.executeUpdate();

		// remove the contact group
		em.remove(cg);
	}

	@Override
	public List<ContactGroup> getGroupsByContactId(int id) {
		Query q = em
				.createQuery("select c.books from Contact c where c.id = :id");
		q.setParameter("id", id);
		List<ContactGroup> cgs = (List<ContactGroup>) q.getResultList();
		return cgs.size() == 0 ? null : cgs;
	}

	public List<ContactGroup> getGroupsByEntId(int id) {
		Query q = em
				.createQuery("select c.books from Enterprise c where c.id = :id");
		q.setParameter("id", id);
		List<ContactGroup> cgs = (List<ContactGroup>) q.getResultList();
		return cgs.size() == 0 ? null : cgs;
	}
}
